package com.liqiye.paymanager.service.payment;

import com.liqiye.paymanager.constant.PaymentPlatform;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class PaymentServiceFactory {

    private final Map<PaymentPlatform, PaymentService> serviceMap;

    public PaymentServiceFactory(List<PaymentService> services) {
        this.serviceMap = services.stream().collect(Collectors.toMap(
            service -> {
                if (service instanceof StripePaymentService) return PaymentPlatform.STRIPE;
                if (service instanceof PayPalPaymentService) return PaymentPlatform.PAYPAL;
                if (service instanceof AdyenPaymentService) return PaymentPlatform.ADYEN;
                if (service instanceof CheckoutPaymentService) return PaymentPlatform.CHECKOUT;
                throw new IllegalArgumentException("Unknown service: " + service.getClass());
            },
            Function.identity()
        ));
    }

    public PaymentService getService(PaymentPlatform platform) {
        return Optional.ofNullable(serviceMap.get(platform))
                .orElseThrow(() -> new IllegalArgumentException("Unsupported platform: " + platform));
    }

}
